<template>
    <el-dialog
            title="扫码登录"
            :visible.sync="dialogVisible"
            width="60%"
            :before-close="handleClose">
        <div class="code" style="width: 180rem;height: 180rem">
            <img style="width: 100%;height: 100%;" :src="qrCode" >
        </div>
    </el-dialog>
</template>

<script>
    import { mapGetters,mapMutations } from "vuex"
    import { getLoginKey,getLoginQrCode,getLoginCookie,getLoginStatus } from "../api/http.js"
  export default {
    name: "user-login",
    data() {
      return {
        qrCode:"",
        unikey:'',
        loginState:null,
        timer:null
      };
    },
    computed:{
      ...mapGetters(["dialogVisible","isLogin"]),
      isLoginState(){
        return this.$store.state.dialogVisible
      }
    },

    watch:{
      //轮询获取登录状态，保存cookie
        isLoginState:function() {
        this._getLogin()
        if(this.isLoginState){
          this.timer = setInterval(async ()=>{
            const token = await this._getLoginCookie(this.unikey)
            if (this.loginState === 801) {
              return
            } else if (this.loginState === 802) {
              return
            } else if (this.loginState === 803) {
              //用户登录成功后清除定时器
              console.log(this.loginState)
              this.setDialogVisible(false)
              window.sessionStorage.setItem('cookie', token.data.cookie)
              clearInterval(this.timer)
            }
          },5000)
        }else{
          clearInterval(this.timer)
        }
      }
    },
    methods: {
      ...mapMutations(['setDialogVisible','setIsLogin']),
      handleClose(done) {
        this.setDialogVisible(false)
      },
      //获取登录的unikey与二维码
      async _getLogin(){
        const res = await getLoginKey()
        const unikey = res.data.data.unikey
        this.unikey = unikey
        const res1 = await getLoginQrCode(unikey)
        console.log(res1.data.data.qrurl)
        this.qrCode = `https://api.qrserver.com/v1/create-qr-code?data=${res1.data.data.qrurl}`
      },
      //检测登录状态
      async _getLoginCookie(key){
        const codeState = await getLoginCookie(key)
        this.loginState = codeState.data.code
        console.log(this.loginState,codeState)
        return codeState
      }
    }
  };
</script>

<style scoped>

</style>